package com.foreverwin.mes.so.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.so.model.Recipe;
import com.foreverwin.mes.so.model.RecipeParam;
import com.foreverwin.mes.so.model.RecipeView;
import com.foreverwin.mes.so.service.RecipeResrceItemRelService;
import com.foreverwin.mes.so.service.RecipeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Syngna
 * @since 2020-02-04
 */
@Controller
@RequestMapping("/recipes")
public class RecipeController {
    private final Logger logger = LoggerFactory.getLogger(RecipeController.class);

    @Autowired
    public RecipeService recipeService;

    @Autowired
    public RecipeResrceItemRelService recipeResrceItemRelService;

    /**
     * 根据id查询
     *
     * @param id 主键
     * @return
     */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getRecipeById(@PathVariable String id) {
        Recipe result;
        try {
            result = recipeService.selectById(id);
        } catch (Exception e) {
            logger.error("getRecipeById -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getRecipeList(Recipe recipe) {
        List<Recipe> result;
        try {
            EntityWrapper<Recipe> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(recipe);
            result = recipeService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getRecipeList -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage 分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getRecipePageList")
    public AjaxResult getRecipePageList(FrontPage<Recipe> frontPage, Recipe recipe) {
        Page result;
        try {
            String site = CommonMethods.getSite();
            recipe.setSite(site);
            EntityWrapper<Recipe> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(recipe);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                        .like("handle", frontPage.getGlobalQuery())
                        .or().like("site", frontPage.getGlobalQuery())
                        .or().like("recipe", frontPage.getGlobalQuery())
                        .or().like("revision", frontPage.getGlobalQuery())
                        .or().like("used", frontPage.getGlobalQuery())
                        .or().like("currentRevision", frontPage.getGlobalQuery())
                        .or().like("creator", frontPage.getGlobalQuery())
                        .or().like("updater", frontPage.getGlobalQuery())
                ;
            }
            result = recipeService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getRecipePageList -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param recipe 配方编号
     * @param recipe 配方版本
     * @return
     */
    @ResponseBody
    @GetMapping("/_listParams")
    public AjaxResult ListParams(String recipe, String revision) {
        List<RecipeParam> result;
        try {
            String site = CommonMethods.getSite();
            result = recipeService.listParams(site, recipe, revision);
        } catch (Exception e) {
            logger.error("listParams -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 新增配方
     * @param newRecipe
     * @param newRecipeVer
     * @param originRecipe 复制数据自originRecipe配方
     * @param originRecipeVer 复制数据自originRecipeVer版本
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/_add")
    public AjaxResult add(String newRecipe, String newRecipeVer, String originRecipe, String originRecipeVer) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count;
        try {
            recipeService.add(site, user, newRecipe, newRecipeVer, originRecipe, originRecipeVer);
        } catch (Exception e) {
            logger.error("add -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_addParam")
    public AjaxResult addParam(@RequestBody RecipeParam recipeParam) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        try {
            recipeService.addParam(site, user, recipeParam);
        } catch (Exception e) {
            logger.error("addParam -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_updateParam")
    public AjaxResult updateParam(@RequestBody RecipeParam recipeParam) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        try {
            recipeService.updateParam(site, user, recipeParam);
        } catch (Exception e) {
            logger.error("updateParam -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除参数
     *
     * @param recipeView 参数handle列表
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_deleteParams")
    public AjaxResult deleteParams(@RequestBody RecipeView recipeView) {
        String user = CommonMethods.getUser();
        try {
            recipeService.deleteParams(user, recipeView);
        } catch (Exception e) {
            logger.error("deleteParams -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult recipeDelete(@PathVariable("id") String id) {
        int count;
        try {
            count = recipeService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("recipeDelete -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     *
     * @param ids 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids) {
        int count;
        try {
            count = recipeService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("recipeBatchDelete -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("count: " + count);
    }
}